package com.wuuxiang.dynamic.mongo.database;

import com.wuuxiang.dynamic.mongo.context.DynamicMongoContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.MongoDatabaseFactory;

public class DynamicMongoDatabaseFactory extends AbstractDynamicMongoDatabaseFactory {
    private static final Logger log = LoggerFactory.getLogger(DynamicMongoDatabaseFactory.class);

    public DynamicMongoDatabaseFactory(DynamicMongoDatabaseFactoryProvider dynamicMongoDatabaseFactoryProvider) {
        super(dynamicMongoDatabaseFactoryProvider);
    }

    @Override
    public MongoDatabaseFactory determineMongoDatabaseFactory() {
        String name = DynamicMongoContextHolder.peek();

        if (name == null || name.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("dynamic-mongo switch to the datasource named [{}]", dynamicMongoDatabaseFactoryProvider.getPrimaryMongoDatabaseName());
            }
            return this.dynamicMongoDatabaseFactoryProvider.getPrimaryMongoDatabaseFactory();
        }
        MongoDatabaseFactory mongoDatabaseFactory = this.dynamicMongoDatabaseFactoryProvider.getMongoDatabaseFactory(name);
        if (mongoDatabaseFactory == null) {
            throw new RuntimeException("dynamic-mongo could not find a datasource named" + name);
        }
        if (log.isDebugEnabled()) {
            log.debug("dynamic-mongo switch to the datasource named [{}]", name);
        }
        return mongoDatabaseFactory;
    }

}
